import React, { ReactNode, useEffect, useState } from 'react';
import './styles/card.less';
import Icon from '../Icon';
import { Badge } from 'antd';
import BusinessContent from '../../views/BusinessOperation/BusinessContent';
import { useBusiness } from '@/views/Context/BusinessContext';
import { useSelector } from 'react-redux';
import { ignoreBusiness } from '@/views/Context/BusinessContext';
import useSyncState from '@/views/hooks/useSyncState';

interface CardProps {
	title?: string;
	width?: string;
	height: number;
	classname?: string;
	children?: ReactNode[] | any;
}

const Card = (props: CardProps) => {
	const { title, children, width, height, classname = '' } = props;

	const [showIcon, setShowIcon] = useState<boolean>(false);

	const [customerTabsNumbers, setCustomerTabsNumbers] = useState(0);

	const { BusinessTaskMap, business } = useBusiness();

	const [businessData, setBusinessData] = useState<any>({});

	const { session } = useSelector((state: any) => state);

	const [showTabList, setShowTabList] = useState(false);

	const [currentUserName, setCurrenUserName] = useState<string | null>(null);
	const [currentIdx, setCurrenIdx] = useSyncState<number>(0);
	const [customerTabList, setCustomerTabList] = useState<any>([]);
	const [bizHeight, setBizHeight] = useState<number>(0);

	useEffect(() => {
		let data = BusinessTaskMap.getComletedTask();
		console.log(data, business, 'BusinessTaskMap.getComletedTask');
		let newCustomerTabList: any = [];
		setShowTabList(data.length > 1);
		data.map(item => {
			newCustomerTabList.push({
				value: item.data.username,
				read: item.isRead,
				badge: true,
				id: item.data.cmdId,
				response: item.response,
				userRole: item.data.userRole,
				type: item.data.name,
				clientId: item.data.clientId
			});
		});
		setCustomerTabList(newCustomerTabList);
		setCustomerTabsNumbers(0);

		setShowTabList(newCustomerTabList.length > 1);
		setShowIcon(newCustomerTabList.length > 3);
		if (newCustomerTabList.length >= 1) {
			const businessData = newCustomerTabList.find((item: any) => item.value === currentUserName);
			let findIndex = newCustomerTabList.map((item: any) => item.value).indexOf(currentUserName);
			if (findIndex === -1) {
				if (currentIdx() >= newCustomerTabList.length || newCustomerTabList.length === 1) {
					setCurrenIdx(0);
				}
			} else {
				setCurrenIdx(findIndex);
			}
			console.log(findIndex, currentIdx, data.length, findIndex === -1);

			if (businessData) {
				businessData.read = true;
				setBusinessData(businessData);
				BusinessTaskMap.updateComletedTask(businessData.value, true);
			} else {
				console.log('currentIdx:', currentIdx(), newCustomerTabList);
				newCustomerTabList[currentIdx()].read = true;
				setBusinessData(newCustomerTabList[currentIdx()]);
				BusinessTaskMap.updateComletedTask(newCustomerTabList[currentIdx()].value, true);
				setCurrenUserName(newCustomerTabList[currentIdx()].value);
			}
		}
	}, [business]);

	useEffect(() => {
		if (showTabList) {
			setBizHeight(height - 50);
		} else {
			setBizHeight(height);
		}
	}, [height, showTabList]);

	const classNames = `widget-card-container ${classname}`;
	const createSlot = (slotName: string) => {
		let children = props.children;
		if (typeof children === 'object' && !Array.isArray(children)) children = [children];
		if (children)
			for (let el of children) {
				console.log(children, slotName);

				if (el.props.slot === slotName) return el;
			}
		return null;
	};

	const showLeftBtnBadge = () => {
		let data = getNowTabList(customerTabsNumbers - 2, customerTabsNumbers);
		let flag = data.filter((item: { read: any }) => !item.read);
		return flag.length > 0 && customerTabsNumbers != 0;
	};

	const showRightBtnBadge = () => {
		let data = getNowTabList(customerTabsNumbers + 2, customerTabList.length - 1);
		let flag = data.filter((item: { read: any }) => !item.read);
		return flag.length > 0 && customerTabsNumbers + 2 != customerTabList.length - 1;
	};

	const getNowTabList = (start: number, end: number) => {
		let newTabList: any = [];
		customerTabList.forEach((item: any, index: number) => {
			if (index >= start && index <= end) {
				newTabList.push(item);
			}
		});
		return newTabList;
	};

	const getTabList = () => {
		return getNowTabList(customerTabsNumbers, customerTabsNumbers + 2);
	};

	const onClickRight = () => {
		if (customerTabsNumbers + 3 >= customerTabList.length) return;
		let num = customerTabsNumbers;
		setCustomerTabsNumbers((num += 2));
	};

	const onClickLeft = () => {
		if (customerTabsNumbers <= 0) return;
		let num = customerTabsNumbers;
		setCustomerTabsNumbers((num -= 2));
	};

	const checkTab = (id: number, name: string) => {
		let newCustomerNameData = [...customerTabList];
		newCustomerNameData.forEach((item, index) => {
			if ((id && id === item.id) || (name && name === item.value)) {
				item.read = true;
				setBusinessData(item);

				BusinessTaskMap.updateComletedTask(item.value, true);
			}
		});
		setCurrenUserName(name);
		let findIndex = newCustomerNameData.map((item: any) => item.value).indexOf(name);

		if (findIndex === -1) {
			setCurrenIdx(0);
		} else {
			setCurrenIdx(findIndex);
		}
		setCustomerTabList(newCustomerNameData);
	};

	useEffect(() => {
		if (!session.sessionId) {
			setBusinessData({});
			setCustomerTabList([]);
		}
	}, [session]);

	return (
		<div className={classNames} style={{ width: width, height: height + 'px', position: 'relative' }}>
			{/* {createSlot('contents')} */}
			{(customerTabList[0] && !['sendIdCardCollection', 'sendBankCardCollection', 'getGeoLocaltion'].includes(customerTabList[0].type)) && <BusinessContent businessData={businessData} height={bizHeight} />}
			{/* OCR识别结果全部显示 */}
			{(customerTabList[0] && ['sendIdCardCollection', 'sendBankCardCollection', 'getGeoLocaltion'].includes(customerTabList[0].type)) &&  customerTabList.map((data: any) => {
				return <div key={data.id} style={{display: currentUserName === data.value ? 'block' : 'none', height: 'calc(100% - 50px)'}}><BusinessContent businessData={data} height={bizHeight} /></div>
			})}
			{showTabList ? (
				<div className="business-operation-tabs-box">
					{showIcon ? (
						<Badge dot={showLeftBtnBadge()} className="fangkezuohua-badge">
							<Icon classname="icon-widget-fangkezuohua" onClick={onClickLeft} />
						</Badge>
					) : undefined}
					<ul className="business-operation-ul-box" id="business-operation-ul">
						{getTabList().map((item: any, index: number) => {
							return (
								<Badge dot={!item.read} key={index}>
									<li
										className={item.value === currentUserName ? 'active-customerName-tabs' : 'customerName-tabs'}
										onClick={() => {
											checkTab(item.id, item.value);
										}}
									>
										{item.value}
									</li>
								</Badge>
							);
						})}
					</ul>

					{showIcon ? (
						<Badge dot={showRightBtnBadge()} className="fangkeyouhua-badge">
							<Icon classname="icon-widget-fangkeyouhua" onClick={onClickRight} />
						</Badge>
					) : undefined}
				</div>
			) : undefined}
		</div>
	);
};

export default Card;
